require "Common/define"
require "Logic/Config"
require "Common/functions"

FlashGiftManager = {};
local this = FlashGiftManager;

local waitShowQueue = {};
local notOpenList = {};
local showFunList = {};
local waitList = {};
local giftTableData = {};
local serverData = {};
local behaviorTableData = {};

local nowShowActiveId;
local _showGiftNum = G.dataTable["t_global"][tostring(270)].f_int_value;
local _waitGiftNum = G.dataTable["t_global"][tostring(270)].f_int_value;
local _playerGrade = 0;
local isFristAcceptServerData = true;

function FlashGiftManager.init()
    giftTableData = G.dataTable["t_bundleconsumption"];
    behaviorTableData = G.dataTable["t_bundleconsumptioncondition"];
end

function FlashGiftManager.OnDestroy()
    this.isOpenedUI = nil;
end

function FlashGiftManager.saveLocalServerData()
    --Util.SetPlayerPrefs(logicMgr.HeroManager.GetRoleInfo().playerId.."_FlashGiftServerData", getJsonStr(serverData));
end

--处理接收的市场数据
function FlashGiftManager.resCostData(data)
    --data = nil;
    if data == nil or not isFristAcceptServerData then
        return ;
    end
    isFristAcceptServerData = false;
    local time = HelperFunc.GetServerTime();
    serverData = {};
    waitShowQueue = {};
    notOpenList = {};
    showFunList = {};
    waitList = {};
    local list = {};
    for i, v in pairs(data) do
        v.subId = i;
        local tableData = FlashGiftManager.getGiftTableDataById(v.giftId);
        if tableData ~= nil then
            v.endTime = tableData.f_TimeLimit + v.startTime * 0.001;
            if v.endTime > time and tableData.f_MaxCount > v.buyCount then
                serverData[v.subId] = v;
                table.insert(list, v);
            end
        end
    end
    logWarn("后端发来一堆新限时礼包 ")
    this.saveLocalServerData();
    table.sort(list, function (a, b) return a.startTime < b.startTime; end);
    if list[1] ~= nil then
        logicMgr.CostManager.addPopUpTips("UIFlashGift", list[1].subId);
    end
    local time = HelperFunc.GetServerTime();
    for i = 1, #list do
        if not logicMgr.CostManager.isOpenItem(this.getGiftOpenTableDataById(list[i].conditionId)) then
            this.addNotOpenList(list[i].subId);
        else
            if #showFunList < _showGiftNum then
                utimer.timeCall(function( ... )
                    this.removeOneFlashGift(list[i].subId);
                end, (list[i].endTime - time) * 1000, 1);

                this.addShowFunActive(list[i].subId);
            else
                table.insert(waitList, list[i].subId);
            end
        end
    end
end

--
function FlashGiftManager.addFlashGiftByLastData(nowData)
    if nowData == nil then
        return ;
    end
    local time = HelperFunc.GetServerTime();
    local num = #showFunList;
    local flag = true;
    for j = 1, num do
        for i = 1, #showFunList do
            if nowData[tostring(showFunList[i].flashId)] == nil then
                flag = false;
                table.remove(showFunList, i);
                FireEvent(Config.EventType.Fresh_FuncMenuData);
                break;
            end
        end
        if flag then
            break;
        end
    end
    logWarn("后端发来一个新限时礼包 ")
    for k, v in pairs(nowData) do
        v.subId = k;
        local tableData = FlashGiftManager.getGiftTableDataById(v.giftId);
        if tableData ~= nil then
            v.endTime = tableData.f_TimeLimit + v.startTime * 0.001;
            if v.endTime > time and tableData.f_MaxCount > v.buyCount then
                serverData[v.subId] = v;
                if not logicMgr.CostManager.isOpenItem(this.getGiftOpenTableDataById(v.conditionId)) then
                    this.addNotOpenList(v.subId);
                else
                    this.addOneFlashGift(v.subId);
                end
            end
        end
    end
end

--
function FlashGiftManager.getNowActiveId()
    return nowShowActiveId;
end

function FlashGiftManager.getShowFunFlashGiftList()
    return showFunList or {};
end

function FlashGiftManager.getGiftTableDataById(id)
    if id == nil then
        return giftTableData;
    end
    return giftTableData[tostring(id)];
end

function FlashGiftManager.getGiftOpenTableDataById(id)
    if id == nil then
        return behaviorTableData;
    end
    return behaviorTableData[tostring(id)];
end

function FlashGiftManager.getCountTime()
    local data = this.getShowFunFlashGiftList();
    if #data <= 0 then
        return 0;
    end
    local serverData, time;
    for k, v in pairs(data) do
        serverData = logicMgr.FlashGiftManager.getGiftServerDataById(v.flashId);
        if serverData ~= nil then
            time = math.floor(serverData.endTime - HelperFunc.GetServerTime());
            if time > 0 then
                return time;
            end
        end
    end
    --FireEvent(Config.EventType.Fresh_FuncMenuData);
    return 0;
end

function FlashGiftManager.getGiftServerDataById(id)
    if id == nil then
        return serverData;
    end
    return serverData[tostring(id)];
end

--
function FlashGiftManager.removeOneFlashGift(id)
    id = tostring(id);
    local flag = false;
    for i = 1, #showFunList do
        if tostring(showFunList[i].flashId) == id then
            table.remove(showFunList, i);
            serverData[id] = nil;
            flag = true;
            break;
        end
    end
    for i = 1, #waitShowQueue do
        if waitShowQueue[i] == id then
            table.remove(waitShowQueue, i);
            serverData[id] = nil;
            flag = true;
            break;
        end
    end
    for i = 1, #notOpenList do
        if notOpenList[i] == id then
            table.remove(notOpenList, i);
            serverData[id] = nil;
            break;
        end
    end
    this.saveLocalServerData();
    if flag then
        if waitList ~= nil and #waitList > 0 then
            this.addWaitShowQueue(waitList[1]);
            table.remove(waitList, 1);
        end
    end
    FireEvent(Config.EventType.Fresh_FuncMenuData);
end

---弹出礼包
function FlashGiftManager.ShowGift()
    this.updateNotOpenList();
    if waitShowQueue == nil or #waitShowQueue == 0 then
        logWarn("暂无新的限时礼包, 结束")
        return false;
    end
    logWarn("弹出成功")
    nowShowActiveId = waitShowQueue[1];
    waitShowQueue = {};
    this.addShowFunActive(nowShowActiveId);
    if isOpenUI(PanelNames.UIFlashGift) then
        CtrlManager.GetCtrl(PanelNames.UIFlashGift):Refresh(nowShowActiveId);
    else
        showUI(PanelNames.UIFlashGift, nil, nowShowActiveId);
    end

    local serverData = logicMgr.FlashGiftManager.getGiftServerDataById(nowShowActiveId)

    local tb = {}
    tb.sole_id = nowShowActiveId
    if serverData then
        tb.gift_id = serverData.giftId
        tb.condition_id = serverData.conditionId
    end

    TAManager.TrackByDictionary("show_limit_gift", tb)
    return true;
end

function FlashGiftManager.isExistFlashGift(id)
    for i = 1, #showFunList do
        if showFunList[i].flashId == id then
            return true;
        end
    end
    for i = 1, #waitShowQueue do
        if waitShowQueue[i] == id then
            return true;
        end
    end
    for i = 1, #waitList do
        if waitList[i] == id then
            return true;
        end
    end
    for i = 1, #notOpenList do
        if notOpenList[i] == id then
            return true;
        end
    end
    return false;
end

---增加一个未开启的礼包
function FlashGiftManager.updateNotOpenList()
    if notOpenList == nil or #notOpenList <= 0 then
        return ;
    end
    for k, v in pairs(notOpenList) do
        local server = this.getGiftServerDataById(v);
        if logicMgr.CostManager.isOpenItem(this.getGiftOpenTableDataById(server.conditionId)) then
            this.addWaitShowQueue(v);
            table.remove(notOpenList, k);
        end
    end
end
---增加一个未开启的礼包
function FlashGiftManager.addNotOpenList(id)
    logWarn("新增一个未开启的限时礼包 ", id)
    if this.isExistFlashGift(id) then
        return ;
    end
    table.insert(notOpenList, id);
end
---增加一个新限时礼包,放入待展示区或者暂存区
function FlashGiftManager.addOneFlashGift(id)
    logWarn("新增一个限时礼包 ", id)
    if this.isExistFlashGift(id) then
        logWarn("新增失败,重复了 ", id)
        return ;
    end
    logWarn("新增成功 ", id)
    if #waitShowQueue + #showFunList >= _showGiftNum then
        if #waitList < _waitGiftNum then
            table.insert(waitList, id);
        end
    else
        this.addWaitShowQueue(id);
    end
end
---加入待展示区
function FlashGiftManager.addWaitShowQueue(id)
    local server = this.getGiftServerDataById(id);
    local tableData = this.getGiftTableDataById(server.giftId);
    if tableData == nil then
        return;
    end
    if server.endTime <= HelperFunc.GetServerTime() then
        return ;
    end
    if waitShowQueue ~= nil and #waitShowQueue > 0 then
        -- 加入新的时,把未展示的都放入显示区(不再展示)
        for i = 1, #waitShowQueue do
            this.addShowFunActive(waitShowQueue[i]);
        end
    end
    waitShowQueue = {};
    utimer.timeCall(function( ... )
        this.removeOneFlashGift(id);
    end, (server.endTime - HelperFunc.GetServerTime()) * 1000, 1);
    table.insert(waitShowQueue, id);
    --local data = {};
    --server.endTime = tableData.f_TimeLimit + HelperFunc.GetServerTime();
    --server.buyCount = 0;
    --server.flashId = id;
    --serverData[id] = data;
    this.saveLocalServerData();
end
---加入显示区
function FlashGiftManager.addShowFunActive(id)
    if id == nil then
        return ;
    end
    local server = this.getGiftServerDataById(id);
    local tableData = this.getGiftTableDataById(server.giftId);
    if tableData == nil then
        return ;
    end
    local data = {};
    data.f_ID = logicMgr.CostManager._FLASHGIFTID;
    data.flashId = id;
    data.f_FuntionType = 1;
    data.f_Icon = tableData.f_BundleConsumptionIcon;
    data.f_OpenUI = "UIFlashGift";
    data.f_Desc = tableData.f_BundleConsumptionName;
    data.f_HintType = Config.RedDotsType.FlashGift;
    data.f_FuncOpen = Config.FuncOpenType.FlashGift;
    table.insert(showFunList, data);
    FireEvent(Config.EventType.Fresh_FuncMenuData);
end

--- 已遗弃，可删
function FlashGiftManager.getActiveIdByGiftType(type)
    for k, v in pairs(giftTableData) do
        if v.f_BundleConsumptionLevel == _playerGrade and v.f_BundleConsumptionType == type then
            return v.f_BundleConsumptionId;
        end
    end
    return nil;
end

--- 已遗弃，可删
function FlashGiftManager.checkIsNeedAddNewFlashGift(type, value)
    if true then
        return ;
    end
    value = tonumber(value);
    if type == EnumConst.FlashGiftType.MAIN or type == EnumConst.FlashGiftType.TOWER then
        for k, v in pairs(behaviorTableData) do
            if v.f_Condition == type and v.f_ConditionValue == value then
                local id = this.getActiveIdByGiftType(v.f_BundleConsumptionType);
                if id ~= nil then
                    this.addOneFlashGift(id);
                end
                break;
            end
        end
    end
    --if isShow then
    --    this.ShowGift();
    --end
end

function FlashGiftManager.showNewFlashGift()
    if logicMgr.GuideMgr.IsGuiding() or not logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.FlashGift) then
        return false;
    end
    logWarn("行为触发限时礼包弹出")
    return this.ShowGift();
end

---
function FlashGiftManager.buyOneFlashGiftByActiveId(id)
    local serverData = this.getGiftServerDataById(id);
    if serverData == nil then
        return true;
    end
    local tableData = this.getGiftTableDataById(serverData.giftId);
    serverData.buyCount = serverData.buyCount + 1;
    this.saveLocalServerData();
    if serverData.buyCount >= tableData.f_MaxCount then
        this.removeOneFlashGift(id);
        return true;
    end
    return false;
end

function FlashGiftManager.setRedDots(flag)
    this.isOpenedUI = flag;
end
function FlashGiftManager.getRedDots()
    return not this.isOpenedUI;
end

return FlashGiftManager